<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <div class="tips">
            <i class="el-icon-info" />
            <span>总记录数：{{ total }}</span>
          </div>
        </template>
        <template #right>
          <el-button type="warning" size="small"><router-link to="/import">excel导入</router-link></el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button v-checkBtn="'p-em-add'" type="primary" size="small" @click="openDialog">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            type="index"
            :index="setIndex"
          />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <el-image
                style="width: 100px; height: 100px; border-radius: 50%;"
                :src="row.staffPhoto"
              >
                <template #placeholder>
                  <img src="@/assets/common/加载.png" alt="">
                </template>
                <template #error>
                  <img src="@/assets/common/加载失败.png" alt="" width="100%">
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ setformOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" width="180" prop="timeOfEntry">
            <template #default="{row}">{{ setTime(row.timeOfEntry) }}</template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template #default="{row}">
              <el-button v-checkBtn="'p-em-look1'" type="text" size="small" @click="goDetaile(row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmploy(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="query.page"
          :page-sizes="[5, 10]"
          :page-size="query.size"
          layout="total,sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="sizeChange"
          @current-change="currentChange"
        />
        <add-employess ref="add" :visible="isShow" @close-dialog="close" @fechList="fechList" />
        <assign-role :id="curId" :visible="visible" @close="closeAssignRoles" />
      </el-card>
    </div>
  </div>
</template>

<script>
import AddEmployess from './components/add-employess.vue'
import { getEmployeeListAPI, delEmployAPI } from '@/api/employees'
import { getExportData } from '@/utils/excel'
import dayjs from 'dayjs'
import AssignRole from './components/assign-roles.vue'
export default {
  components: {
    AddEmployess,
    AssignRole
  },
  data() {
    return {
      list: [],
      query: {
        page: 1,
        size: 10
      },
      total: 0,
      isShow: false,
      visible: false,
      curId: ''
    }
  },
  mounted () {
    this.fechList()
    // console.log(AddEmployess)
    // console.log(this.$refs.add)
  },
  methods: {
    async fechList() {
      try {
        const res = await getEmployeeListAPI(this.query)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) { console.log(err) }
    },
    setformOfEmployment(value) {
      // 对value进行格式化然后return
      // 1 2 4
      // 枚举写法 一次性列出来所有的对应情况 然后通过对象取值 称之为枚举
      // 比多分支语句对应关系更加清晰 而且方便拓展 如果需要多增加情况的话 只需要在对象中
      // 添加一个新的键值对
      // 枚举：通常少量的 不会发生变化的使用前端枚举即可  大量的变化的必须接口来做
      const TYPE = {
        1: '正式员工',
        2: '非正式员工',
        4: '小舅子'
      }
      return TYPE[value]
    },
    setIndex(index) {
      return ((this.query.page - 1) * this.query.size + index + 1)
    },
    setTime(time) {
      // console.log(time)
      return dayjs(time).format('YYYY-MM-DD')
    },
    sizeChange(size) {
      this.query.size = size
      this.query.page = 1
      this.fechList()
    },
    currentChange(page) {
      this.query.page = page
      this.fechList()
    },
    delEmploy(row) {
      this.$confirm(`确定删除${row.username}此员工信息么`, '提示', { type: 'warning' }).then(async() => {
        const res = await delEmployAPI(row.id).catch(err => console.log(err))
        this.$message.success(res.message)
        if (this.query.size === 1 && this.query.page > 1) {
          this.query.page--
        }
        this.fechList()
      }).catch(() => this.$message.info('取消删除此员工信息'))
    },
    openDialog() {
      this.isShow = true
    },
    close() {
      this.isShow = false
    },
    exportExcel() {
      // 1. import 语法叫做动态导入语法 常见于比较大的包，而且还不一定要用的场景 什么时候用什么时候导入
      // 2.import方法执行结果是一个promise对象
      import('@/vendor/Export2Excel').then(async excel => {
        // excel表示导入的模块对象
        // 可以获取其中的方法
        // 1.请求接口获取当前页数据
        const res = await getEmployeeListAPI(this.query)
        console.log(res)
        const headerRelation = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        // getExportData这个方法的返回值是一个对象 所以需要结构
        const { data } = getExportData(res.data.rows, headerRelation)
        console.log(data)
        excel.export_json_to_excel({
          header: Object.keys(headerRelation), // ['姓名', '工资'], // 表头 必填
          data,
          // : [
          //   ['刘备', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: '员工数据', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
        this.$message.success('导出员工列表成功')
      })
    },
    goDetaile(id) {
      this.$router.push(`/detaile?id=${id}`)
    },
    assignRoles(id) {
      this.visible = true
      this.curId = id
    },
    closeAssignRoles() {
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
